<?php
declare(strict_types=1);

namespace App\Controller\Admin;

use App\Annotation\ModuleAndAction;
use App\Exception\BusinessException;
use App\Helper\FileHelper;
use App\Middleware\AdminMiddleware;
use App\Model\ContentStatic;
use Hyperf\HttpMessage\Upload\UploadedFile;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use stdClass;

/**
 * @AutoController()
 * @ModuleAndAction(module="管理后台:内容管理:素材管理", icon="fa fa-puzzle-piece")
 * @Middleware(AdminMiddleware::class)
 */
class StaticController extends BaseController
{
    public $model = ContentStatic::class;

    protected function fixListData(?array $data): ?array
    {
        $data || $data = [];
        /* @var stdClass $item */
        foreach ($data as $i => $item) {
            $data[$i]->url = ContentStatic::getUrl($item->path, $item->extension);
        }
        $item = new stdClass();
        $item->id = 0;
        $item->path = '';
        $item->title = '';
        $item->extension = '';
        array_unshift($data, $item);
        return $data;
    }

    protected function fixPostData(?array $data): ?array
    {
        $request = $this->request;
        if (!$request) {
            return null;
        }
        $uploads = $request->getUploadedFiles();
        /* @var UploadedFile $uploadFile */
        $uploadFile = $uploads['file'] ?? null;
        $id = intval($data['id'] ?? 0);
        $path = strval($data['path'] ?? '');
        $extension = strval($data['extension'] ?? '');
        $title = strval($data['title'] ?? '');
        if ($id == 0) {
            if (is_null($uploadFile)) {
                return null;
            }
            empty($title) && $title = $uploadFile->getClientFilename();
            $path = ContentStatic::genPath();
            $extension = $uploadFile->getExtension();
            $extension && $extension = '.' . $extension;
            $fullPath = ContentStatic::getRealPath($path, $extension);
            FileHelper::del($fullPath, ContentStatic::PATH_ROOT);
            FileHelper::makeDir(dirname($fullPath), 0777, ContentStatic::PATH_ROOT);
            $uploadFile->moveTo($fullPath);
            if ($uploadFile->isMoved()) {
                return compact('path', 'extension', 'title');
            }
            return null;
        }
        $doUpdate = true;
        if ($uploadFile) {
            empty($title) && $title = $uploadFile->getClientFilename();
            $fullPath = ContentStatic::getRealPath($path, $extension);
            FileHelper::del($fullPath, ContentStatic::PATH_ROOT);
            FileHelper::makeDir(dirname($fullPath), 0777, ContentStatic::PATH_ROOT);
            $uploadFile->moveTo($fullPath);
            $doUpdate = $uploadFile->isMoved();
        }
        if ($doUpdate) {
            return compact('id', 'title');
        }
        return null;
    }

    protected function afterDeleted(int $rowsCount, array $idsArr, bool $soft): array
    {
        unset($idsArr, $soft);
        if (!$rowsCount) {
            throw new BusinessException(0, '没有任何数据被删除!');
        }
        $post = $this->request->post();
        $path = strval($post['path'] ?? '');
        $extension = strval($post['extension'] ?? '');
        if (!empty($path)) {
            $fullPath = ContentStatic::getRealPath($path, $extension);
            FileHelper::del($fullPath, ContentStatic::PATH_ROOT);
        }
        return ['rows_count' => $rowsCount];
    }

    protected function afterCreated($newId, array $post): array
    {
        if (!$newId) {
            throw new BusinessException(0, '数据库插入失败,未得到新ID!');
        }
        $path = strval($post['path'] ?? '');
        $extension = strval($post['extension'] ?? '');
        return ['src' => ContentStatic::getUrl($path, $extension)];
    }

    protected function afterUpdated($rowsCount, $id, $post): array
    {
        unset($post);
        if (!$rowsCount) {
            throw new BusinessException(0, '没有任何数据改变!');
        }
        $model = ContentStatic::find($id);
        if (!$model) {
            throw new BusinessException(0, '按ID:' . $id . ' 未找到数据!');
        }
        return ['src' => $model->url];
    }
}
